package com.common.base.widget.indicator

import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.widget.LinearLayout

abstract class IndicatorView : LinearLayout {

    private var current = -1

    constructor(context: Context) : super(context) {
        init(context, null)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) {
        init(context, attrs)
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init(context, attrs)
    }

    private fun init(context: Context, attrs: AttributeSet?) {
        gravity = Gravity.CENTER
        orientation = HORIZONTAL
    }

    fun set(current: Int, size: Int) {
        removeAllViews()
        for(i in 0 until size) {
            addView(createIndicatorItemView())
        }
        this.current = -1
        select(current, false)
    }

    fun select(current: Int, isAnimation: Boolean) {
        if(this.current == current)
            return
        val oldItem = getChildAt(this.current)
        val item = getChildAt(current)
        this.current = current
        oldItem?.let {
            if(it is IndicatorItemView) {
                it.unselect(isAnimation)
            }
        }
        item?.let {
            if(it is IndicatorItemView) {
                it.select(isAnimation)
            }
        }
    }

    abstract fun createIndicatorItemView(): IndicatorItemView
}